package com.imageim.yimirror.service.weather;

import android.os.AsyncTask;

import com.imageim.yimirror.base.BaseApplication;
import com.imageim.yimirror.common.network.EnhancedHttpHelper;
import com.imageim.yimirror.common.network.ThreadPoolManager;
import com.imageim.yimirror.common.util.CacheKey;
import com.imageim.yimirror.common.util.CacheUtils;
import com.imageim.yimirror.common.util.JsonUtil;
import com.imageim.yimirror.service.weather.bean.WeatherDetail;
import com.imageim.yimirror.service.weather.bean.WeatherItem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Bruce.Zhou on 2018/6/6.
 */
public class WeatherUtil {

    public interface WeatherListener {
        void onStart();
        void onSuccess(WeatherDetail weatherDetail);
        void onFail(int errorCode);
    }

    /**
     * 来自聚合数据天气预报
     * @param cityName
     * @param weatherListener
     */
    public static void getWeather(final String cityName, final WeatherListener weatherListener) {
        if (cityName == null) {
            return;
        }
        loadWeatherFromLocal(weatherListener);
        new AsyncTask<String, Integer, WeatherDetail>() {

            @Override
            protected void onPreExecute() {
                weatherListener.onStart();
            }

            @Override
            protected WeatherDetail doInBackground(String... strings) {
                try {
                    String city = URLEncoder.encode(cityName, "utf-8");
                    String weatherJson = EnhancedHttpHelper.getString("http://op.juhe.cn/onebox/weather/query" +
                            "?key=674c4a8f9dbe5ad6b1fcecb14d46e46f&cityname=" + city, 1);

                    JSONObject jsonObject = new JSONObject(weatherJson);
                    int errorCode = jsonObject.getInt("error_code");
                    if (errorCode == 0) { // 查询成功
                        WeatherDetail weather = new WeatherDetail();
                        JSONObject data = jsonObject.getJSONObject("result").getJSONObject("data");
                        // realtime
                        JSONObject realTime = data.getJSONObject("realtime");
                        String date = realTime.getString("date");
                        int week = realTime.getInt("week");
                        weather.setDate(date);
                        weather.setWeek(week);
                        JSONObject realTimeWeather = realTime.getJSONObject("weather");
                        String temperature = realTimeWeather.getString("temperature");
                        String info = realTimeWeather.getString("info");
                        int img = realTimeWeather.getInt("img");
                        weather.setTemperature(temperature);
                        weather.setImg(img);
                        weather.setInfo(info);
                        // life
                        JSONObject life = data.getJSONObject("life");
                        String chuanyi = life.getJSONObject("info").getJSONArray("chuanyi").getString(1);
                        weather.setChuanYi(chuanyi);
                        JSONArray futureWeather = data.getJSONArray("weather");
                        List<WeatherItem> items = new ArrayList<WeatherItem>();
                        if (futureWeather != null && futureWeather.length() > 0) {
                            for (int i = 0; i < futureWeather.length(); i++) {
                                WeatherItem item = new WeatherItem();
                                JSONObject weatherItem = futureWeather.getJSONObject(i);
                                date = weatherItem.getString("date");
                                String weekStr = weatherItem.getString("week");
                                String nongli = weatherItem.getString("nongli");
                                JSONObject infoObj = weatherItem.getJSONObject("info");
                                JSONArray dawn = infoObj.getJSONArray("dawn");
                                JSONArray day = infoObj.getJSONArray("day");
                                JSONArray night = infoObj.getJSONArray("night");
                                String dayInfo = day.getString(1);
                                String dayTemperature = day.getString(2);
                                String dayWind = day.getString(3) + " " + day.getString(4);
                                String nightInfo = night.getString(1);
                                String nightTemperature = night.getString(2);
                                String nightWind = night.getString(3) + " " + night.getString(4);
                                String dayOutAdvise = day.optString(6);
                                String nightOutAdvise = night.optString(6);
                                String dawnWind = dawn.getString(3) + " " + dawn.getString(4);
                                item.setDate(date);
                                item.setWeak(weekStr);
                                item.setInfoDay(dayInfo);
                                item.setNongli(nongli);
                                item.setTemperatureDay(dayTemperature);
                                item.setWindDay(dayWind);
                                item.setWindDawn(dawnWind);
                                item.setInfoNight(nightInfo);
                                item.setTemperatureNight(nightTemperature);
                                item.setWindNight(nightWind);
                                item.setDayOutAdvise(dayOutAdvise);
                                item.setNightOutAdvise(nightOutAdvise);
                                items.add(item);
                            }
                        }
                        weather.setWeather(items);
                        return weather;
                    } // 查询成功
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(WeatherDetail weatherDetail) {
                if (weatherDetail != null) {
                    setWeather2Cache(weatherDetail);
                    weatherListener.onSuccess(weatherDetail);
                } else {
                    loadWeatherFromLocal(weatherListener);
                    weatherListener.onFail(1);
                }
            }
        }.executeOnExecutor(ThreadPoolManager.getInstance().getThreadPool());
    }

    private static void loadWeatherFromLocal(WeatherListener weatherListener) {
        weatherListener.onStart();
        WeatherDetail weatherDetail = getWeatherFromCache();
        if (weatherDetail != null) {
            weatherListener.onSuccess(weatherDetail);
        } else {
            weatherListener.onFail(1);
        }
    }

    public static void setWeather2Cache(WeatherDetail weather) {
        CacheUtils.setString(BaseApplication.getContext(), CacheKey.weatherDetail, JsonUtil.gson.toJson(weather));
    }

    public static WeatherDetail getWeatherFromCache() {
        String json = CacheUtils.getString(BaseApplication.getContext(), CacheKey.weatherDetail);
        return JsonUtil.gson.fromJson(json, WeatherDetail.class);
    }


}
